package com.easy.web.utils;

import org.apache.commons.collections.MapUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.dom4j.dom.DOMText;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Administrator on 2017/3/29.
 */
public class WeiXinUtil {

    /**
     * 根据参数对象生成签名
     *
     * @param paramMap 参数对象
     * @return 返回签名
     */
    public static String generateSign(String apiKey, Map<String, String> paramMap) {
        if (MapUtils.isEmpty(paramMap)) return null;
        StringBuilder sb = new StringBuilder();
        paramMap.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
        sb.append("key=").append(apiKey);
        return EncryptUtils.md5Encrypt(sb.toString()).toUpperCase();
    }

    /**
     * 验证响应数据
     * @param respStr 响应数据字符串
     * @return 返回参数，返回null表示验证没通过
     */
    public static Map<String, String> verifyResp(String apiKey, String respStr) throws DocumentException {
        SAXReader sax = new SAXReader();
        sax.setEncoding(StandardCharsets.UTF_8.name());
        StringReader reader = new StringReader(respStr);
        Document document = sax.read(reader);
        Element rootElement = document.getRootElement();
        List<Element> eleList = rootElement.elements();

        String sign = null;
        Map<String, String> map = new TreeMap<>();
        for (Element ele : eleList) {
            if ("sign".equals(ele.getName())) {
                sign = ele.getStringValue();
            } else {
                map.put(ele.getName(), ele.getStringValue());
            }
        }
        String s = WeiXinUtil.generateSign(apiKey, map);
        if (s != null && sign != null && s.equals(sign)) {
            return map;
        } else {
            return null;
        }
    }

    /**
     * 生成请求参数
     *
     * @param paramMap 参数对象
     * @return 返回xml字符串
     */
    public static String buildXmlBody(Map<String, String> paramMap) {
        Document document = DocumentFactory.getInstance().createDocument(StandardCharsets.UTF_8.name());
        DOMElement rootEle = new DOMElement("xml");
        document.add(rootEle);
        paramMap.forEach((k, v) -> {
            DOMElement ele = new DOMElement(k);
            ele.add(new DOMText(v));
            rootEle.add(ele);
        });
        return document.asXML();
    }
}
